package org.game.db;

import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import org.constant.RemoteServerType;
import org.remote.social.RemoteSocialServer;
import org.utils.RemoteUtil;

import com.sojoys.artifact.constant.ArtifactErrorCode;
import com.sojoys.artifact.factory.distributedId.IDistributedIdProvider;
import com.sojoys.artifact.manager.RemoteProxyManager;
import com.sojoys.artifact.manager.ThreadManager;
import com.sojoys.artifact.tools.ToolError;

/**
 * @author : DengYing
 * @CreateDate : 2017年10月16日 下午6:41:55
 * @Description ：Please describe this document
 */
public class SnowflakeIdProvider implements IDistributedIdProvider {

	private SnowflakeIdProvider() {
	}

	private static SnowflakeIdProvider ME = new SnowflakeIdProvider();

	public static SnowflakeIdProvider me() {
		return ME;
	}

	private ConcurrentLinkedQueue<Long> primaryKeys = new ConcurrentLinkedQueue<>();
	private AtomicInteger primaryKeyCount = new AtomicInteger();

	

	@Override
	public long pollId() {
		ToolError.isAndTrue(ArtifactErrorCode.SNOWFLAKE_ERROR, primaryKeys.isEmpty());
		long id = primaryKeys.poll();
		int count = primaryKeyCount.decrementAndGet();
		if (count < 250) {
			asynLoad();
		}
		return id;
	}
	
	public void syncLoad() {
		List<Long> ids = RemoteUtil.socialSync().getIds();
		primaryKeyCount.addAndGet(ids.size());
		primaryKeys.addAll(ids);
	}
	
	public void asynLoad(){
		ThreadManager.me().execute("taskExecutor", () -> syncLoad());
	}
}
